#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>

using namespace std;

class Solution {
public:
    int byteNum = 1;
    int oneByte = 0x7F;
    int twoByte = 0xE0;
    int threeByte = 0xF0;
    int fourByte = 0xF8;
    int speByte = 0xC0;
public:
    bool validUtf8(vector<int>& data) {
        for (const auto& num : data) {
            if (isOneByte(num) == true) {
                continue;
            }

            if (isMultiByte(num) == true) {
                continue;
            }
            return false;
        }

        if (byteNum != 1) {
            return false;
        }
        return true;
    }

    bool isOneByte(int num)
    {
        if (byteNum != 1) {
            return false;
        }

        int tmp = num | oneByte;
        if (tmp != oneByte) {
            return false;
        }

        return true;
    }

    bool isMultiByte(int num)
    {
        int tmp;
        if (byteNum == 1) {
            tmp = num & twoByte;
            if (tmp == 0xC0) {
                byteNum = 2;
                return true;
            }
            tmp = num & threeByte;
            if (tmp == 0xE0) {
                byteNum = 3;
                return true;
            }
            tmp = num & fourByte;
            if (tmp == 0xF0) {
                byteNum = 4;
                return true;
            }
            return false;
        }

         tmp = num & speByte;
        if (tmp == 0x80) {
            byteNum--;
            return true;
        }

        return false;
    }
};

int main()
{
    Solution s;
    vector<int> vt{240,162,138,147};
    cout << boolalpha << s.validUtf8(vt) << endl;
    // cout << boolalpha << s.isMultiByte(235) << endl;

    return 0;
}